<script lang="ts" setup>
import moment from 'moment'
import { ContactApi } from '~/api/ContactApi'
import { JobRecordApi } from '~/api/JobRecordApi'
import LxButton from '~/components/common/LxButton.vue'
import PairsView from '~/components/common/PairsView.vue'
import { ContactModel, JobRecordModel } from '~/model'
import { SalaryModel } from '~/model/SalaryModel'
import { ScheduleModel } from '~/model/ScheduleModel'

const route = useRoute()
const router = useRouter()

const id = ref(0)
const worker = ref(new ContactModel())
const records = ref([] as JobRecordModel[])
const salaryModel = computed(() => new SalaryModel(records.value))
const scheduleModel = computed(() => new ScheduleModel(records.value))

onMounted(() => {
  id.value = Number.parseInt(route.query.id as string)
  ContactApi.getAll()
    .then((res) => {
      worker.value = res.find(x => x.id === id.value)!
    })
  JobRecordApi.getAll()
    .then((res) => {
      const ret = res.filter(x => x.worker!.id === id.value)

      // console.log('?');
      // console.log(ret.map(x => x.date.valueOf()));

      ret.sort((a, b) => b.date.valueOf() - a.date.valueOf())
      records.value = ret
      JobRecordModel.sort(records.value, true)
    })
})

function goDetail(row: JobRecordModel) {
  router.push(`/jobs/events/detail?id=${row.id}`)
}

function dateFormatter(r: JobRecordModel) {
  return moment(r.date).format('MM/DD')
}

function contentFormatter(r: JobRecordModel) {
  return r.description()
}

function goEvent() {
  router.push(`/jobs/events/detail?event=1&worker=${worker.value.id}`)
}

function goContact() {
  router.push(`/contacts/detail?id=${id.value}`)
}
</script>

<template>
  <div>
    <PairsView
      v-if="worker.id && records.length"
      :pairs="[
        ['姓名', worker.name],
        ['月薪', salaryModel.currentMonthlySalary().toString()],
        ['排班', scheduleModel.getSchedule()],
      ]"
    />

    <PairsView
      v-if="worker.id && records.length"
      :pairs="[
        ['工作天数', salaryModel.totalWorkDays().toString()],
        ['薪资总计', salaryModel.totalShouldSent().toString()],
        ['已发', salaryModel.totalAdvance().toString()],
        ['未发', salaryModel.totalShouldSentRemaining().toString()],
      ]"
    />

    <div mb2 flex>
      <LxButton title="创建事务" color="mediumseagreen" icon="plus" :action="goEvent" />
      <LxButton title="联系" :action="goContact" color="darkorange" icon="phone" />
    </div>

    <table class="lx-table">
      <thead>
        <tr>
          <th>日期</th>
          <th>事务</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="record in records" :key="record.id" @click="goDetail(record)">
          <td>{{ dateFormatter(record) }}</td>
          <td>{{ contentFormatter(record) }}</td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<route lang="yaml">
meta:
  title: 工人详情
</route>
